package com.kakavr.alipay.controller;

import java.util.Enumeration;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;
import com.kakavr.alipay.service.IAlipayService;
import com.kakavr.base.controller.BaseController;
import com.kakavr.result.Result;
@RestController
@RequestMapping("n/alipay")
public class AlipayController extends BaseController {
	@Resource
	private IAlipayService alipayService;
	
	/**
	 * 支付宝通知
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "alipayNotify", method = RequestMethod.POST)
	public void notifyAliPay(HttpServletRequest request, HttpServletResponse response){
		debug("支付宝后端通知===================================---begin");
		Map<String, String> map = this.initZFBParams(request);
		info("支付宝后端通知参数："+map);
		try {
			boolean checkBoolean = alipayService.checkZFBSign(map);
			if (checkBoolean){
				if(alipayService.updateAlipayLogByNotify(map)){
					Result.outJson("success", response);
				}
			}
		} catch (Exception e) {
			error("支付宝返回响应处理逻辑出错，错误信息：" + e);
			return;
		}
		debug("支付宝通知=============================================---end");
		Result.outJson("fail", response);
	}
	
	
	/**
	 * 支付宝页面调整
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "alipayReturn", method = RequestMethod.GET)
	public ModelAndView alipayReturn(HttpServletRequest request){
		debug("支付宝前端返回===================================---begin");
		Map<String, String> map = this.initZFBParams(request);
		try {
			boolean checkBoolean = alipayService.checkZFBSign(map);
			if(checkBoolean){
				return new ModelAndView("redirect:/mach/pay_success.html");
			}
		} catch (Exception e) {
			error("支付宝返回响应处理逻辑出错，错误信息：" + e);
			return new ModelAndView("redirect:/mach/pay_fail.html");
		}
		debug("支付宝前端返回=============================================---end");
		return new ModelAndView("redirect:/mach/pay_fail.html");
	}
	
	private Map<String, String> initZFBParams(HttpServletRequest request) {
		Map<String, String> params = Maps.newHashMap();
		Enumeration<String> enumeration = request.getParameterNames();
		while (enumeration.hasMoreElements()) {
			String name = (String) enumeration.nextElement();
			String[] values = request.getParameterValues(name);
			if (values.length == 0) {
				params.put(name, null);
			} else if (values.length == 1) {
				params.put(name, values[0]);
			}
		}
		return params;
	}

}
